<?php
/*************************************************************************************
   Copyright notice

   This script uses some code parts of the glossary module for phpwcms (c) Oliver Georgi
   (c) 2002-2009 Oliver Georgi (oliver@phpwcms.de) // All rights reserved.

   This script uses some code parts from bmcatalog module
   (c) 2010 Benjamin Matzmorr, www.etype.de

   (c) 2012 webrealisierung gmbh, www.webrealisierung.ch
   Catalogue Module V 1.0.0  -  Date: 2012-06-01

   The GNU General Public License can be found at http://www.gnu.org/copyleft/gpl.html
   A copy is found in the textfile GPL.txt and important notices to the license
   from the author is found in LICENSE.txt distributed with these scripts.

   This script is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details.

   This copyright notice MUST APPEAR in all copies of the script!
*************************************************************************************/

// Module/Plug-in Catalogue search class
class ModuleCatalogueSearch {

	var $search_words			= array();
	var $search_result_entry	= 0;
	var $search_results			= array();
	var $search_highlight		= false;
	var $search_highlight_words	= false;
	var $search_wordlimit		= 0;
	var $ellipse_sign			= '&#8230;';

  var $plugin_ctg_sresult_acontent = array(); //container array
  var $plugin_ctg_active = array();  //[artid][array active cals in this article]
  var $plugin_ctg_cals = array(); //all calendars
  var $plugin_ctg_sresult = array(); //container articles

    //get the catalogs from module
	function ctg_get_cals() {
    $sql = "SELECT * FROM ".DB_PREPEND."phpwcms_mod_catalogue_catalog WHERE ctgc_status=1";
    $this->plugin_ctg_cals =  _dbQuery($sql);
  }

    //get the catids(ID) of catalogs selected in any contentparts in any articles
    //and set the $plugin_ctg_active
    //it's not super perfect cause more or less the same thing is done in the standard search yet
	function ctg_get_articles() {

 		$sql  = "SELECT article_id, article_cid, article_title, article_username, article_subtitle, ";
		$sql .= "article_summary, article_keyword, UNIX_TIMESTAMP(article_tstamp) AS article_date ";
		$sql .= "FROM ".DB_PREPEND."phpwcms_article ar ";
		$sql .= "LEFT JOIN ".DB_PREPEND."phpwcms_articlecat ac ON ";
		$sql .= "(ar.article_cid = ac.acat_id OR ar.article_cid = 0)";
		$sql .= " WHERE ";
		// limit to special structure IDs if not all
		if(count($content["search"]["start_at"])) {
			$sql .= 'ar.article_cid IN ('.implode(',', $content["search"]["start_at"]).')';
		} else {
			$sql .= "IF(ar.article_cid = 0, " . (empty($GLOBALS['indexpage']['acat_nosearch']) ? 1 : 0) .", 1)";
		}
		$sql .= " AND ac.acat_nosearch != 1 AND ac.acat_aktiv=1 AND ac.acat_public=1 AND ";
		if(!FEUSER_LOGIN_STATUS) {
			$sql .= "ac.acat_regonly=0 AND ";
		}
		$sql .= "ar.article_public=1 AND ar.article_aktiv=1 AND ar.article_deleted=0 AND ar.article_nosearch!=1 AND ";
		// enhanced IF statement by kh 2008/12/03
		$sql .= "IF((ar.article_begin < NOW() AND ar.article_end > NOW()) OR (ar.article_archive_status=1 AND ac.acat_archive=1), 1, 0) ";
		$sql .= "GROUP BY ar.article_id";
  	$this->plugin_ctg_sresult = _dbQuery($sql);

      foreach($this->plugin_ctg_sresult as $row) {
				// read article content for search
				$cm_art_sql  = "SELECT acontent_aid, acontent_type, acontent_form FROM ";
				$cm_art_sql .= DB_PREPEND."phpwcms_articlecontent WHERE acontent_aid=".$row["article_id"]." ";
				$cm_art_sql .= "AND acontent_module='br_catalogue' "; //only module ctg
				$cm_art_sql .= "AND acontent_visible=1 AND acontent_trash=0 AND ";
				if( !FEUSER_LOGIN_STATUS ) {
					$cm_art_sql .= 'acontent_granted=0 AND ';
				}
				$cm_art_sql .= "acontent_type = 30"; //only modules
  	    $this->plugin_ctg_sresult_acontent = _dbQuery($cm_art_sql);

          foreach ($this->plugin_ctg_sresult_acontent as $artrow) {

            $artrow['acontent_form'] = @unserialize($artrow['acontent_form']);


              $plugin_ctg_art = array();
                 foreach($this->plugin_ctg_cals as $value_cal) {
                  if (in_array($value_cal['ctgc_id'], $artrow['acontent_form']['ctg_catalogs'])){
                    array_push($plugin_ctg_art, $value_cal['ctgc_id']);
                  }
                 }

              //return array[article ID]array[#]int[cm_cat_id] - array() when no result
              $this->plugin_ctg_active[$artrow['acontent_aid']] =  $plugin_ctg_art;


          }
      }

  }

    //get the search result from db ctg entries
    //for each result in each eventlisting in each article
    //meaning when acalendar entry appears in two eventlsitings it will appear in two search results as well
	function search() {
	
		if(count($this->search_words)==0) {
			return NULL;
		} else {
			$this->search_words = implode('|', $this->search_words);
		}

    foreach($this->plugin_ctg_active as $activekey => $activevalue) {

        $plugin_ctg_events = array();
        $calsarray = array();
      //prepare sql for different catalogs
        foreach($activevalue as $val) {
            $calsarray[] = "ctge_catalogid LIKE '%|".intval($val)."|%'";
      	}
        $wherequery = (count($calsarray)) ? " AND (".implode(' OR ', $calsarray).")" : "";

        $plugin_ctg_events["sql"]  = 'SELECT * FROM '.DB_PREPEND.'phpwcms_mod_catalogue_entry WHERE ';
      	$plugin_ctg_events["sql"] .= "ctge_status = 1";
      	$plugin_ctg_events["sql"] .= $wherequery;
      	$plugin_ctg_events["sql"] .= " ORDER BY ctge_title ASC";
      	$plugin_ctg_events["data"] = _dbQuery($plugin_ctg_events["sql"]);

        foreach($plugin_ctg_events["data"] as $value) {
		
    			$s_result	= array();
          $s_text = $value['ctge_title2'] .' '. $value['ctge_text'] .' '. $value['ctge_text2'] .' '. $value['ctge_address_address'] .' '. $value['ctge_address_city'];
					$s_text = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $s_text); // strip all <script> Tags
    			$s_text		= str_replace( array('~', '|', ':', 'http', '//', '_blank', '&nbsp;') , ' ', $s_text );
    			$s_text		= clean_replacement_tags($s_text, '');
    			$s_text		= remove_unsecure_rptags($s_text);
    			$s_text		= cleanUpSpecialHtmlEntities($s_text);

          $s_text2 = $value['ctge_title'];
					$s_text2 = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $s_text2); // strip all <script> Tags
    			$s_text2		= str_replace( array('~', '|', ':', 'http', '//', '_blank', '&nbsp;') , ' ', $s_text2 );
    			$s_text2		= clean_replacement_tags($s_text2, '');
    			$s_text2		= remove_unsecure_rptags($s_text2);
    			$s_text2		= cleanUpSpecialHtmlEntities($s_text2);
			
          preg_match_all('/'.$this->search_words.'/is', $s_text2.' '.$s_text, $s_result );

          $s_count	= 0; //set search_result to 0
          foreach($s_result as $svalue) {
  				  $s_count += count($svalue);
          }
			
			    if($s_count) {

            $id = $this->search_result_entry;

            $s_title  = $value['ctge_title'];
            $s_title  = html_specialchars($s_title);

            $s_text   = trim($s_text);
            $s_text   = getCleanSubString($s_text, $this->search_wordlimit, $this->ellipse_sign, 'word');
            $s_text   = html_specialchars($s_text);

            $this->search_results[$id]["id"]	= $value['ctge_id'];
            $this->search_results[$id]["cid"]	= 0;
            $this->search_results[$id]["rank"]	= $s_count;
            $this->search_results[$id]["title"]	= $this->search_highlight ? highlightSearchResult($s_title, $this->search_highlight_words) : $s_title;
            $this->search_results[$id]["user"]	= '';
            $this->search_results[$id]['query']	= 'aid='.$activekey.'&ctg_id='.$value['ctge_id'];

            if($this->search_highlight) {
            	$s_text = highlightSearchResult($s_text, $this->search_highlight_words);
            }
            $this->search_results[$id]["text"]	= $s_text;

            $this->search_result_entry++;
          }
        }
    }

  }

}
?>